<?php

namespace app\admin\controller;

use app\comm\func\CommFunc;
use app\comm\func\Consts;
use think\Controller;
use think\Request;
use think\Session;
use think\Db;

/**
 * Class Score 成绩模块
 * @package app\admin\controller
 */
class Score extends Controller
{
    /**
     * @param Request $request 成绩列表
     * @return mixed
     */
    public function ScoreList(Request $request)
    {
        if ($request->isPost()) {
            $condition = $request->post();
            if (count($condition) == 1) {
                $student = Db::table('student')
                    ->where('student_name', 'like', '%' . $condition['name'] . '%')
                    ->paginate(5, true);
                $this->SeachScore($student);
                return $this->fetch();
            } else {
                if ($condition['score'] > 100 || $condition['score'] < 0 || empty($condition['score'])) {
                    return exit;
                }
                $student = Db::table('student')->where('id', $condition['id'])->find();
                $classroom = Db::table('classroom')->where('cid', $student['classroom'])->find();
                $res = Db::table('score')
                    ->where('student_id', $condition['id'])
                    ->where('classroom', $classroom['cid'])->where('stage', $classroom['stage'])->find();
                $arr = json_decode($res['examination'], true);
                $arr[$condition['examination']] = $condition['score'];
                $arr = json_encode($arr);
                $updateType = Db::table('score')
                    ->where('student_id', $condition['id'])
                    ->where('stage', $classroom['stage'])->data('examination', $arr)->update();
                if ($updateType > 0) {
                    CommFunc::ajaxReturn(Consts::$successful);
                } else {
                    CommFunc::ajaxReturn(Consts::$failure);
                }
            }
        } else {
            $role_id = Session::get('auth')['role_id'];
            if ($role_id == 1) {
                $student = Db::table('student')->paginate(5, true);
                $this->SeachScore($student);
                return $this->fetch();
            } else {
                $teacher_id = Session::get('auth')['aid'];
                $teacherClassMaxIdDb = Db::table('teacher_class')
                    ->where('teacher_id', $teacher_id)->max('id');
                $teacherClass = Db::table('teacher_class')
                    ->where('id', $teacherClassMaxIdDb)->find();
                $studentAll = Db::table('student')
                    ->where('classroom', $teacherClass['classroom_id'])
                    ->where('teacher', $teacher_id)->select();
                foreach ($studentAll as $key => $vo) {
                    $studentAll[$key]['classroom'] = Db::table('classroom')
                        ->where('cid', $vo['classroom'])->find();
                    $studentAll[$key]['teacher'] = Db::table('admin')
                        ->where('aid', $studentAll[$key]['classroom']['teacher_id'])
                        ->find();
                    $studentAll[$key]['score'] = Db::table('score')
                        ->where('student_id', $vo['id'])
                        ->where('classroom', $vo['classroom'])
                        ->where('stage', $teacherClass['stage'])
                        ->find();
                    $studentAll[$key]['score'] = json_decode($studentAll[$key]['score']['examination'], true);
                    $studentAll = $this->Avg($studentAll, $key);
                }
                $this->assign('student', $studentAll);
                return $this->fetch();
            }
        }
    }

    /**
     * 查询
     * @param array $student
     * @return array|mixed
     */
    public function SeachScore($student = [])
    {
        $page = $student->render();
        $student = $student->all();
        foreach ($student as $key => $vo) {
            $student[$key]['classroom'] = Db::table('classroom')
                ->where('cid', $vo['classroom'])->find();
            $student[$key]['teacher'] = Db::table('admin')
                ->where('aid', $student[$key]['classroom']['teacher_id'])->find();
            $student[$key]['score'] = Db::table('score')
                ->where('student_id', $vo['id'])
                ->where('classroom', $student[$key]['classroom']['cid'])
                ->where('stage', $student[$key]['classroom']['stage'])
                ->find();
            $student[$key]['score'] = json_decode($student[$key]['score']['examination'], true);
            $student = $this->Avg($student, $key);
        }
        $this->assign(['student' => $student, 'page' => $page]);
        return $student;
    }

    /**
     * 根据不同周考算出平均值
     * @param $studentAll
     * @param $key  数组的键
     * @return mixed    返回处理过得数组
     */
    public function Avg($studentAll, $key)
    {
        $avgCount = 0;
        $emptyCount = 0;
        foreach ($studentAll[$key]['score'] as $k => $v) {
            $v = intval($v);
            if ($v != 0) {
                $emptyCount++;
            }
            if ($emptyCount == 0) {
                $studentAll[$key]['avg'] = 0;
            } else {
                $avgCount += $v;
                $studentAll[$key]['avg'] = intval($avgCount / $emptyCount);
            }
        }
        return $studentAll;
    }

    /**
     * 日常成绩操作以及计算
     * @param Request $request
     * @return mixed
     */
    public function EveryDay(Request $request)
    {
        if ($request->isPost()) {
            $condition = $request->post();  //获取到时间,学生id,选择的access
            if (!empty($condition['checktime'])) {
                /* 用户选择了时间,那就说明用户是想去修改那天的记录就可以去表中update */
                /*第一步 首先得获取到传来的是哪一天的*/
                $formerlyTime = strtotime($condition['checktime']);  //用户选择的日期
                /*第二步 获取该学生在该班级,该阶段有哪些日常记录*/
                $student_id = $condition['id'];
                $classroom_id = Db::table('student')->where('id', $student_id)->field('classroom')->find();
                $stage = Db::table('classroom')->where('cid', $classroom_id['classroom'])->field('stage')->find();
                $recordTime = Db::table('everyday')
                    ->where('student_id', $student_id)
                    ->where('classroom', $classroom_id['classroom'])
                    ->where('stage', $stage['stage'])->select();
                foreach ($recordTime as $key => $item) {
                    $record[$key]['recordTime'] = date('Y-m-d', $item['time']);
                    $record[$key]['time'] = strtotime($record[$key]['recordTime']);
                    $record[$key]['id'] = $item['id'];
                }
                /* 获取到用户输入时间的那一条记录的id号 */
                $res = [];
                foreach ($record as $key => $value) {
                    if ($formerlyTime == $value['time']) {
                        $res = $value;
                    }
                }
                $everyId = $res['id'];
                /* 以该ID号为条件,将记录更新至表中*/
                /* 判断添加的记录是否已经被记录 */
                $Selected = Db::table('everyday')->where('id', $everyId)->find();  /* 查出该ID号的日常记录 */
                $SelectedOption = json_decode($Selected['option'], true); /* 已经记录的option */
                if (empty($condition['access'])) {
                    return exit;
                }
                $nowOption = $condition['access']; //当前选择的option
                $newOption = array_unique(array_merge($SelectedOption, $nowOption));
                if (empty($newOption)) {
                    CommFunc::ajaxReturn(Consts::$failure);
                }
                $newOption = array_values($newOption);
                $new = json_encode($newOption);
                Db::startTrans();
                $result = Db::table('everyday')->where('id', $everyId)->data([
                    'option' => $new
                ])->update();
                if ($result > 0) {
                    $this->EveryScoreCount($condition);
                } else {
                    Db::rollback();
                    CommFunc::ajaxReturn(Consts::$failure);
                }
            } else {
                /* 用户没有选择时间 */
                $arr['time'] = time();
                $arr['student_id'] = $condition['id'];
                $arr['option'] = $condition['access'];
                $Previous_record_id = Db::table('everyday')
                    ->where('student_id', $condition['id'])->max('id');
                $record = Db::table('everyday')->where('id', $Previous_record_id)->find();
                $present = $arr['time'];
                $record_time = date('Y-m-d', $record['time']);
                $present_time = date('Y-m-d', $present);
                if ($record_time == $present_time) {   //计算是否是当天
                    $findOption = json_decode($record['option'], true);
                    if (!empty($findOption)) {
                        $arr['option'] = array_unique(array_merge($arr['option'], $findOption));
                    }
                    $arr['option'] = array_values($arr['option']);
                    $arr['option'] = json_encode($arr['option']);
                    Db::startTrans();
                    $updateType = Db::table('everyday')->where('student_id', $arr['student_id'])
                        ->where('id', $record['id'])
                        ->data([
                            'time' => $arr['time'],
                            'option' => $arr['option']
                        ])->update();
                    if ($updateType > 0) {
                        $this->EveryScoreCount($condition);
                    } else {
                        CommFunc::is_RollBack();
                    }
                } else { //不是当天就新增
                    $arr['option'] = json_encode($arr['option']);
                    $everyMaxId = Db::table('everyday')
                        ->where('student_id', $arr['student_id'])->max('id');
                    $everySult = Db::table('everyday')->where('id', $everyMaxId)->find();
                    $arr['classroom'] = $everySult['classroom'];
                    $arr['stage'] = $everySult['stage'];
                    Db::startTrans();
                    $insertType = Db::table('everyday')->insert($arr);
                    if ($insertType > 0) {
                        $this->EveryScoreCount($condition);
                    } else {
                        CommFunc::is_RollBack();
                    }
                }
            }
        } else {
            CommFunc::emptyVerify($request->param(), ['id']);
            CommFunc::conditionAdd($condition, $request->param(), ['id']);
            $res = Db::table('option')->select();
            $this->assign(['option' => $res, 'id' => $condition['id']]);
            return $this->fetch();
        }
    }

    /**
     * 日常详情
     */
    public function EveryDetails(Request $request)
    {
        /* 获取前台传过来的学生ID */
        CommFunc::emptyVerify($request->param(), ['id']);
        CommFunc::conditionAdd($condition, $request->param(), ['id']);
        /* 根据学生ID查出该学生所在班级,阶段的所有日常记录 */
        $classroom_id = Db::table('student')
            ->where('id', $condition['id'])
            ->field('classroom')->find();
        $stage = Db::table('classroom')
            ->where('cid', $classroom_id['classroom'])
            ->field('stage')->find();
        $res = Db::table('everyday')
            ->where('student_id', $condition['id'])
            ->where('classroom', $classroom_id['classroom'])
            ->where('stage', $stage['stage'])
            ->select();
        $result = [];
        foreach ($res as $key => $vo) {
            $result[$key]['options'] = json_decode($vo['option'], true);
            $result[$key]['time'] = date('Y-m-d', $vo['time']);
            if (!empty($result[$key]['options'])){
                foreach ($result[$key]['options'] as $k => $v){
                    $res = Db::table('option')->where('id',$v)->find();
                    $result[$key]['option'][$k] = $res['option_name'];
                }
            }
        }
        $this->assign('res',$result);
        return $this->fetch();
    }

    /**
     * @param $condition
     */
    public function EveryScoreCount($condition)
    {
        $student = Db::table('student s')
            ->join('classroom c', 's.classroom=c.cid', 'left')
            ->where('id', $condition['id'])->find();
        $options = Db::table('everyday')
            ->where('student_id', $student['id'])
            ->where('classroom', $student['cid'])
            ->where('stage', $student['stage'])
            ->field('option')
            ->select();
        foreach ($options as $key => $vo) {
            if (!empty($vo['option'])) {
                $every[] = json_decode($vo['option'], true);
            }
        }
        foreach ($every as $key => $vo) {
            foreach ($vo as $k => $v) {
                $optionScore[] = Db::table('option')->where('id', $v)->find();
            }
        }
        $EveryDayScore = 0;
        foreach ($optionScore as $key => $value) {
            $EveryDayScore += $value['option_score'];
        }
        $EveryDayScore = 100 - $EveryDayScore;
        $score = Db::table('score')->where('student_id', $student['id'])
            ->where('classroom', $student['cid'])
            ->where('stage', $student['stage'])->find();
        $score = json_decode($score['examination'], true);
        $score['everyday'] = $EveryDayScore;
        $score = json_encode($score);
        $scoreType = Db::table('score')
            ->where('student_id', $student['id'])
            ->where('classroom', $student['cid'])
            ->where('stage', $student['stage'])
            ->data(['examination' => $score])->update();
        if ($scoreType > 0) {
            Db::commit();
            CommFunc::ajaxReturn(Consts::$successful);
        } else {
            CommFunc::is_RollBack();
        }
    }

    /**
     * 个人成绩详情页
     * @param Request $request
     */
    public function ScoreDetails(Request $request)
    {
        CommFunc::emptyVerify($request->param(), ['id']);
        CommFunc::conditionAdd($condition, $request->param(), ['id']);
        $studentScore = Db::table('score')->where('student_id', $condition['id'])->select();
        foreach ($studentScore as $key => $value) {
            $value['classroom'] = Db::table('classroom')->where('cid', $value['classroom'])->field('class_name')->find();
            $value['examination'] = json_decode($value['examination'], true);
            $res[$value['classroom']['class_name']][$value['stage']] = ['examination' => $value['examination']];
        }
        $this->assign('res', $res);
        return $this->fetch();
    }
}